<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="盘点单号" prop="takingCode">
        <el-input
          v-model="queryParams.takingCode"
          placeholder="请输入盘点单号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仓库名称" prop="warehouseName">
        <el-input
          v-model="queryParams.warehouseName"
          placeholder="请输入仓库名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="盘点状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择盘点状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['inventory:check:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['inventory:check:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['inventory:check:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['inventory:check:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="checkList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="盘点单号" align="center" prop="takingCode" />
      <el-table-column label="仓库名称" align="center" prop="warehouseName" />
      <el-table-column label="盘点类型" align="center" prop="takingType">
        <template slot-scope="scope">
          <dict-tag :options="typeOptions" :value="scope.row.takingType"/>
        </template>
      </el-table-column>
      <el-table-column label="盘点状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="statusOptions" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="盘点差异" align="center" prop="differenceQuantity">
        <template slot-scope="scope">
          <span :class="scope.row.differenceQuantity > 0 ? 'text-danger' : (scope.row.differenceQuantity < 0 ? 'text-success' : '')">
            {{ scope.row.differenceQuantity }}
          </span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleDetail(scope.row)"
            v-hasPermi="['inventory:check:query']"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['inventory:check:edit']"
            v-if="scope.row.status === '0'"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['inventory:check:remove']"
            v-if="scope.row.status === '0'"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-check"
            @click="handleSubmit(scope.row)"
            v-hasPermi="['inventory:check:submit']"
            v-if="scope.row.status === '0'"
          >提交</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-check"
            @click="handleApprove(scope.row)"
            v-hasPermi="['inventory:check:approve']"
            v-if="scope.row.status === '1'"
          >审核</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-close"
            @click="handleCancel(scope.row)"
            v-hasPermi="['inventory:check:cancel']"
            v-if="scope.row.status === '0' || scope.row.status === '1'"
          >取消</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 审核对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="审核结果" prop="approveStatus">
          <el-radio-group v-model="form.approveStatus">
            <el-radio label="2">通过</el-radio>
            <el-radio label="3">驳回</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见" prop="approveComment">
          <el-input v-model="form.approveComment" type="textarea" placeholder="请输入审核意见"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listInventoryCheck, getInventoryCheck, delInventoryCheck, submitCheck, approveCheck, cancelCheck } from "@/api/inventory/check";

export default {
  name: "Check",
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 库存盘点表格数据
      checkList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 审核状态字典
      approveStatusOptions: [{
        dictLabel: "通过",
        dictValue: "2"
      }, {
        dictLabel: "驳回",
        dictValue: "3"
      }],
      // 盘点状态字典
      statusOptions: [{
        dictLabel: "草稿",
        dictValue: "0"
      }, {
        dictLabel: "进行中",
        dictValue: "1"
      }, {
        dictLabel: "已完成",
        dictValue: "2"
      }, {
        dictLabel: "已取消",
        dictValue: "3"
      }],
      // 日期范围
      dateRange: [],
      // 表单参数
      form: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        takingCode: null,
        warehouseName: null,
        status: null
      },
      // 表单校验
      rules: {
        approveStatus: [
          { required: true, message: "审核结果不能为空", trigger: "change" }
        ],
        approveComment: [
          { required: true, message: "审核意见不能为空", trigger: "blur" }
        ]
      },
      // 类型数据字典
      typeOptions: [
        { dictLabel: "全面盘点", dictValue: "1" },
        { dictLabel: "动态盘点", dictValue: "2" },
        { dictLabel: "周期盘点", dictValue: "3" }
      ]
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询库存盘点列表 */
    getList() {
      this.loading = true;
      listInventoryCheck(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.checkList = response.rows;
        this.total = response.total;
        this.loading = false;
      }).catch(error => {
        console.error("获取盘点列表失败:", error);
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        takingId: undefined,
        approveStatus: "2",
        approveComment: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.takingId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push("/ck/Stocktaking/add");
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const takingId = row.takingId || this.ids[0];
      this.$router.push(`/ck/Stocktaking/add?id=${takingId}`);
    },
    /** 查看详情按钮操作 */
    handleDetail(row) {
      this.$router.push(`/ck/Stocktaking/detail/${row.takingId}`);
    },
    /** 提交按钮操作 */
    handleSubmit(row) {
      const takingId = row.takingId;
      this.$modal.confirm('是否确认提交盘点单号为"' + row.takingCode + '"的盘点数据？').then(function() {
        return submitCheck(takingId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("提交成功");
      }).catch(error => {
        console.error("提交失败:", error);
      });
    },
    /** 审核操作 */
    handleApprove(row) {
      this.reset();
      this.form.takingId = row.takingId;
      this.open = true;
      this.title = "审核盘点单";
    },
    /** 取消盘点单 */
    handleCancel(row) {
      const takingId = row.takingId;
      this.$modal.confirm('是否确认取消盘点单号为"' + row.takingCode + '"的盘点单？').then(function() {
        return cancelCheck(takingId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("取消成功");
      }).catch(error => {
        console.error("取消失败:", error);
      });
    },
    /** 提交审核 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          approveCheck(this.form).then(response => {
            this.$modal.msgSuccess("审核成功");
            this.open = false;
            this.getList();
          }).catch(error => {
            console.error("审核失败:", error);
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const takingIds = row.takingId || this.ids;
      
      // 检查是否有ID
      if (!takingIds || (Array.isArray(takingIds) && takingIds.length === 0)) {
        this.$modal.msgError("请选择要删除的记录");
        return;
      }
      
      // 获取盘点单号
      let takingCode = "";
      if (row && row.takingCode) {
        takingCode = row.takingCode;
      } else if (this.ids.length === 1) {
        // 如果是单个选择，尝试从列表中找到对应的盘点单号
        const selectedItem = this.checkList.find(item => item.takingId === this.ids[0]);
        if (selectedItem) {
          takingCode = selectedItem.takingCode;
        }
      }
      
      const confirmMessage = takingCode ? 
        `是否确认删除盘点单号为"${takingCode}"的数据项？` : 
        `是否确认删除选中的${Array.isArray(takingIds) ? takingIds.length : 1}条数据？`;
      
      this.$modal.confirm(confirmMessage).then(function() {
        return delInventoryCheck(takingIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(error => {
        console.error("删除失败:", error);
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('inventory/check/export', {
        ...this.queryParams
      }, `库存盘点_${new Date().getTime()}.xlsx`);
    }
  }
};
</script>

<style scoped>
.text-danger {
  color: #F56C6C;
}
.text-success {
  color: #67C23A;
}
</style> 